import Axios from "axios";
import { BASE_API_URL, USER_TOKEN_NAME } from "../config";

import {
  XHR_PENDING,
  XHR_FULFILLED,
  XHR_REJECTED,
  XHR_IDLE,
} from "../config/index";

const instance = Axios.create({
  baseURL: BASE_API_URL,
});

instance.interceptors.request.use(
  (config) => {
    if (localStorage.getItem(USER_TOKEN_NAME)) {
      config.headers.Authorization = `Bearer ${localStorage.getItem(
        USER_TOKEN_NAME
      )}`;
    }
    config.headers["Accept-Language"] = "fa_IR";

    return config;
  },
  (error) => Promise.reject(error)
);

instance.interceptors.response.use(
  (response) => response.data,
  (error) => {
    let errorBody;
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      errorBody = {
        data: error.response.data,
        status: error.response.status,
      };
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      errorBody = {
        data: error.request,
      };
    } else {
      // Something happened in setting up the request that triggered an Error
      errorBody = {
        data: error.message,
      };
    }
    return Promise.reject(errorBody);
  }
);

export default instance;

export type RequestHandler = {
  status: string;
  data: any | null;
  error: any | null;
  isLoading: boolean;
};

export const reqIdlePayload: RequestHandler = {
  status: XHR_IDLE,
  data: null,
  error: null,
  isLoading: false,
};

export const reqPendingPayload = {
  status: XHR_PENDING,
  data: null,
  error: null,
  isLoading: true,
};

export const reqFulfilledPayload = (res: any) => ({
  status: XHR_FULFILLED,
  data: res,
  error: null,
  isLoading: false,
});

export const reqRejectedPayload = (err: { data: string[] }) => ({
  status: XHR_REJECTED,
  data: null,
  error: err.data,
  isLoading: false,
});
